﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;

namespace MagicCove
{
    static class GameFunctions
    {
        #region Handle Card Images
        static String cardImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Magic Cove\Card Images\";
        static String tokenImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Magic Cove\Card Images\Tokens\";
        public static Image getCardImage(String cardName)
        {
            if (!System.IO.File.Exists(cardImagesPath + cardName + ".jpg"))
            { //get image to harddrive then return the gotten image
                String cardAddress = "http://www.magiccards.info/query?q=!" + cardName + "&v=card&s=cname";
                // used to build entire input
                StringBuilder sb = new StringBuilder();

                // used on each read operation
                byte[] buf = new byte[8192];

                // prepare the web page we will be asking for
                HttpWebRequest request = (HttpWebRequest)
                    WebRequest.Create(cardAddress);
                //Need to try catch next command to check internet. Catch display message you are not connected to the internet.
                // execute the request
                HttpWebResponse response = (HttpWebResponse)
                    request.GetResponse();

                // we will read data via the response stream
                Stream resStream = response.GetResponseStream();

                string tempString = null;
                int count = 0;

                do
                {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?

                // print out page source
                String pageSC = sb.ToString();
                try
                {
                    //Get Url
                    int picSI = pageSC.IndexOf("<img src") + 10;
                    int picEI = pageSC.IndexOf("<p>");
                    String picTempSubS1 = pageSC.Substring(picSI, picEI - picSI);
                    picSI = picTempSubS1.IndexOf("<img src") + 10;
                    String picTempSubS2 = picTempSubS1.Substring(picSI, picTempSubS1.Length - picSI);
                    picEI = picTempSubS2.IndexOf("\"");
                    String picUrl = picTempSubS2.Substring(0, picEI);
                    //Pic Disp
                    System.Net.WebClient source = new System.Net.WebClient();
                    Stream myData = source.OpenRead(picUrl);
                    System.Drawing.Bitmap cardPic = new System.Drawing.Bitmap(myData);
                    myData.Close();
                    //image box set to stretch so no need to size manually
                    saveJpeg(cardImagesPath + cardName + ".jpg", cardPic, 100);
                }
                catch
                {
                    return null;
                }
            }

            return Image.FromFile(cardImagesPath + cardName + ".jpg");
        }
        public static Image getTokenImage(String tokenName, String tokenURL)
        {
            // a "/" cannot be in the file name, so it is replaced by a -
            String tokenSavedPictureName = tokenName.Replace("/", "-");
            tokenSavedPictureName = tokenSavedPictureName.Replace("*", "X");
            if (!System.IO.File.Exists(tokenImagesPath + tokenSavedPictureName + ".jpg"))
            { //get image to harddrive then return the gotten image
                try
                {
                    //Pic Disp
                    System.Net.WebClient source = new System.Net.WebClient();
                    Stream myData = source.OpenRead(tokenURL);
                    System.Drawing.Bitmap tokenPic = new System.Drawing.Bitmap(myData);
                    myData.Close();
                    //image box set to stretch so no need to size manually
                    saveJpeg(tokenImagesPath + tokenSavedPictureName + ".jpg", tokenPic, 100);
                }
                catch
                {
                    return null;
                }
            }

            return Image.FromFile(tokenImagesPath + tokenSavedPictureName + ".jpg");
        }
        private static void saveJpeg(string path, Bitmap img, long quality)
        {
            // Encoder parameter for image quality
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            // Jpeg image codec
            ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg");

            if (jpegCodec == null)
                return;

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            img.Save(path, jpegCodec, encoderParams);
        }
        private static ImageCodecInfo getEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
        #endregion
        public static void downloadCardData(MagicCard mC)
        {//takes a magic card and updates its information according to what it fetched from the internet based on mC.CardName
            //Feteches the following info:
                //Mana Cost
                //Card sub-type,type,supertype
            throw new NotImplementedException("Skeleton Function");
            //get page source
            //(remember to search with ! as searched for when getting image)
            //extract mana cost

            //extract types
        }
        public static String stripDeck(String deckS)
        {//strips deck of all comment lines
            StringBuilder temp = new StringBuilder(); //new deck with all comments stipped, and empty ("junk") lines removed
            while (deckS.Length > 0)
            {
                if (deckS.IndexOf("\n") <= deckS.IndexOf("-") && !deckS.StartsWith(":") && !deckS.StartsWith("<") && deckS.IndexOf("Sideboard") != 0)//there is an empty or badly formatted line
                {//ignore line
                    if (deckS.IndexOf("\n") == -1) //last line
                        deckS = "";
                    else //ignore line
                        deckS = deckS.Substring(deckS.IndexOf("\n") + 1, deckS.Length - (deckS.IndexOf("\n") + 1));
                }
                else if (deckS.IndexOf("\n") == -1)//last line of the file
                {
                    if (!deckS.StartsWith(">"))
                        temp.Append(deckS);
                    deckS = "";
                }
                else
                {
                    if (!deckS.StartsWith(">"))
                    {
                        temp.Append(deckS.Substring(0, deckS.IndexOf("\n") + 1));
                    }
                    deckS = deckS.Substring(deckS.IndexOf("\n") + 1, deckS.Length - (deckS.IndexOf("\n") + 1));
                }
            }
            return temp.ToString();
        }
        public static List<MagicCard> reorderMCList(List<MagicCard> mCL)
        {
            ReorderListForm reorderForm = new ReorderListForm(mCL);
            reorderForm.ShowDialog();
            List<MagicCard> retVal = reorderForm.ReorderedList;
            reorderForm.Dispose();
            return retVal;
        }
    }
}